<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryFormRef" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目" prop="projectId">
        <el-select v-model="queryParams.projectId" placeholder="请选择项目" clearable @change="onQueryProjectChange">
          <el-option v-for="p in projectOptions" :key="p.projectId" :label="p.projectName" :value="p.projectId" />
        </el-select>
      </el-form-item>
      <el-form-item label="任务" prop="taskId">
        <el-select v-model="queryParams.taskId" placeholder="请选择任务" clearable filterable>
          <el-option v-for="t in taskOptions" :key="t.taskId" :label="t.taskName" :value="t.taskId" />
        </el-select>
      </el-form-item>
      <el-form-item label="成员" prop="userId">
        <el-select v-model="queryParams.userId" placeholder="请选择成员" clearable filterable>
          <el-option v-for="m in memberOptions" :key="String(m.userId)" :label="m.nickName" :value="String(m.userId)" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="handleQuery">
          <el-icon><Search /></el-icon>搜索
        </el-button>
        <el-button size="small" @click="resetQuery">
          <el-icon><Refresh /></el-icon>重置
        </el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" size="small" @click="handleAdd" v-hasPermi="['pm:time:add']">
          <el-icon><Plus /></el-icon>新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" size="small" :disabled="multiple" @click="handleDelete" v-hasPermi="['pm:time:remove']">
          <el-icon><Delete /></el-icon>删除
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="项目" align="center" prop="projectName" />
      <el-table-column label="任务" align="center" prop="taskName" />
      <el-table-column label="成员" align="center" prop="userName">
        <template #default="scope">
          {{ scope.row.userName || getUserNickName(scope.row.userId) }}
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="startTime" width="170" />
      <el-table-column label="结束时间" align="center" prop="endTime" width="170" />
      <el-table-column label="时长(h)" align="center" prop="duration" />
      <el-table-column label="可计费" align="center" prop="isBillable">
        <template #default="scope">
          <el-tag :type="scope.row.isBillable ? 'success' : 'info'">{{ scope.row.isBillable ? '是' : '否' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="费率" align="center" prop="hourlyRate" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button size="small" type="primary" @click="handleView(scope.row)" v-hasPermi="['pm:time:query']">
            <el-icon><View /></el-icon>查看
          </el-button>
          <el-button size="small" type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['pm:time:edit']">
            <el-icon><Edit /></el-icon>修改
          </el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)" v-hasPermi="['pm:time:remove']">
            <el-icon><Delete /></el-icon>删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="项目" prop="projectId">
          <el-select v-model="form.projectId" placeholder="请选择项目" :disabled="isView" @change="onFormProjectChange">
            <el-option v-for="p in projectOptions" :key="p.projectId" :label="p.projectName" :value="p.projectId" />
          </el-select>
        </el-form-item>
        <el-form-item label="任务" prop="taskId">
          <el-select v-model="form.taskId" placeholder="请选择任务" :disabled="isView" filterable>
            <el-option v-for="t in taskOptions" :key="t.taskId" :label="t.taskName" :value="t.taskId" />
          </el-select>
        </el-form-item>
        <el-form-item label="成员" prop="userId">
          <el-select 
            v-model="form.userId" 
            placeholder="请选择成员" 
            :disabled="isView" 
            filterable
            multiple
            collapse-tags
            collapse-tags-tooltip
            popper-class="member-select-popper"
          >
            <el-option 
              v-for="m in memberOptions" 
              :key="m.userId" 
              :label="m.nickName" 
              :value="m.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker 
            v-model="form.startTime" 
            type="datetime" 
            placeholder="选择开始时间" 
            :disabled="isView"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker 
            v-model="form.endTime" 
            type="datetime" 
            placeholder="选择结束时间" 
            :disabled="isView"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="时长(h)" prop="duration">
          <el-input-number v-model="form.duration" :min="0" :max="9999" :step="0.25" :disabled="isView" />
        </el-form-item>
        <el-form-item label="可计费" prop="isBillable">
          <el-switch v-model="form.isBillable" :disabled="isView" />
        </el-form-item>
        <el-form-item label="费率" prop="hourlyRate">
          <el-input-number v-model="form.hourlyRate" :min="0" :max="999999" :step="10" :disabled="isView" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" v-model="form.description" placeholder="请输入描述" :disabled="isView" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm" v-if="!isView">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, getCurrentInstance, watch } from 'vue'
import type { FormInstance } from 'element-plus'
import { listTime, startTime, stopTime, saveTime, delTime } from '@/api/pm/time'
import { listProject, getProjectMembers } from '@/api/pm/project'
import { listTask, getTaskTree } from '@/api/pm/task'
import { listUser } from '@/api/system/user'
import RightToolbar from '@/components/RightToolbar/index.vue'
import Pagination from '@/components/Pagination/index.vue'
import { Search, Refresh, Plus, Edit, Delete, View } from '@element-plus/icons-vue'

const { proxy } = getCurrentInstance() as any

const formRef = ref<FormInstance>()
const queryFormRef = ref<FormInstance>()

const loading = ref(true)
const ids = ref<number[]>([])
const multiple = ref(true)
const showSearch = ref(true)
const total = ref(0)
const list = ref<any[]>([])
const title = ref("")
const open = ref(false)
const isView = ref(false)

// 下拉选项
const projectOptions = ref<any[]>([])
const taskOptions = ref<any[]>([])
const memberOptions = ref<any[]>([])

const queryParams = reactive<any>({
  pageNum: 1,
  pageSize: 10,
  projectId: undefined,
  taskId: undefined,
  userId: undefined
})

const form = ref<any>({
  id: undefined,
  projectId: undefined,
  taskId: undefined,
  userId: [],
  startTime: undefined,
  endTime: undefined,
  duration: 0,
  isBillable: false,
  hourlyRate: 0,
  description: ''
})

const rules = reactive({
  projectId: [{ required: true, message: '项目ID不能为空', trigger: 'blur' }],
  userId: [{ required: true, message: '用户ID不能为空', trigger: 'blur' }]
})

onMounted(() => {
  initProjects()
  getList()
})

const initProjects = () => {
  listProject({ pageNum: 1, pageSize: 9999 }).then(res => {
    // 兼容 rows/data
    projectOptions.value = (res.rows || res.data || [])
    console.debug('加载项目完成, 数量=', projectOptions.value.length)
    // 若未选择项目且已有项目数据，默认选第一个，自动触发任务/成员加载
    if (!queryParams.projectId && projectOptions.value.length > 0) {
      queryParams.projectId = projectOptions.value[0].projectId
      console.debug('默认选择项目=', queryParams.projectId)
      onQueryProjectChange(queryParams.projectId)
    }
  }).catch(err => {
    console.error('加载项目列表失败', err)
    projectOptions.value = []
  })
}

const loadTasksByProject = (projectId?: string | number) => {
  taskOptions.value = []
  if (!projectId) return
  listTask({ projectId, pageNum: 1, pageSize: 9999 }).then(res => {
    taskOptions.value = (res.rows || res.data || [])
    if ((!taskOptions.value || taskOptions.value.length === 0) && projectId) {
      // 兜底：尝试任务树接口
      getTaskTree(projectId).then(treeRes => {
        const flat: any[] = []
        const dfs = (arr: any[]) => arr.forEach(n => { flat.push(n); if (n.children) dfs(n.children) })
        const data = (treeRes.data || []) as any[]
        dfs(data)
        taskOptions.value = flat
      }).catch(err => console.error('任务树兜底失败', err))
    }
  }).catch(err => {
    console.error('加载任务列表失败', err)
    taskOptions.value = []
  })
}

const loadMembersByProject = (projectId?: string | number) => {
  memberOptions.value = []
  if (!projectId) {
    return
  }
  // 直接加载所有用户，然后过滤出项目相关的用户
  listUser({ pageNum: 1, pageSize: 1000 }).then(res => {
    const allUsers = res.rows || []
    
    // 获取项目成员，提取用户ID列表
    getProjectMembers(projectId).then(memberRes => {
      const members = memberRes.data || []
      const projectUserIds = new Set()
      
      // 收集所有项目相关的用户ID
      members.forEach(member => {
        if (member.userId && typeof member.userId === 'string') {
          const userIds = member.userId.split(',').map(id => id.trim()).filter(Boolean)
          userIds.forEach(userId => projectUserIds.add(userId)) // 直接使用字符串
        }
      })
      
      // 过滤出项目相关的用户
      memberOptions.value = allUsers.filter(user => {
        const userIdStr = String(user.userId)
        return projectUserIds.has(userIdStr)
      })
    }).catch(err => {
      console.error('加载项目成员失败', err)
      memberOptions.value = []
    })
  }).catch(err => {
    console.error('加载用户列表失败', err)
    memberOptions.value = []
  })
}

const getList = () => {
  loading.value = true
  listTime(queryParams).then(res => {
    list.value = res.rows || []
    total.value = res.total || 0
    
    // 加载成员数据用于显示昵称
    if (queryParams.projectId) {
      loadMembersByProject(queryParams.projectId)
    }
  }).finally(() => loading.value = false)
}

const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

const resetQuery = () => {
  proxy?.$nextTick(() => queryFormRef.value?.resetFields())
  handleQuery()
}

const onQueryProjectChange = (projectId?: string | number) => {
  console.debug('查询区项目变更 => 触发加载任务/成员, projectId=', projectId)
  loadTasksByProject(projectId)
  loadMembersByProject(projectId)
  // 清空已选任务/成员，避免跨项目残留
  queryParams.taskId = undefined
  queryParams.userId = undefined
}

const onFormProjectChange = (projectId?: string | number) => {
  loadTasksByProject(projectId)
  loadMembersByProject(projectId)
  form.value.taskId = undefined
  form.value.userId = []
}

// 监听项目选择，确保无论何时赋值都能触发加载
watch(() => queryParams.projectId, (val) => {
  if (val) {
    onQueryProjectChange(val)
  }
})

watch(() => form.value.projectId, (val) => {
  if (val) {
    onFormProjectChange(val)
  }
})

const handleSelectionChange = (selection: any[]) => {
  ids.value = selection.map(item => item.id)
  multiple.value = !selection.length
}

const reset = () => {
  form.value = {
    id: undefined,
    projectId: undefined,
    taskId: undefined,
    userId: [],
    startTime: undefined,
    endTime: undefined,
    duration: 0,
    isBillable: false,
    hourlyRate: 0,
    description: ''
  }
  proxy?.$nextTick(() => formRef.value?.resetFields())
}

const handleAdd = () => {
  reset()
  isView.value = false
  open.value = true
  title.value = '新增时间记录'
}

const handleView = (row: any) => {
  reset()
  form.value = { ...row }
  // 将单个用户ID转换为数组格式
  form.value.userId = row.userId ? [row.userId] : []
  loadTasksByProject(form.value.projectId)
  loadMembersByProject(form.value.projectId)
  isView.value = true
  open.value = true
  title.value = '查看时间记录'
}

const handleUpdate = (row: any) => {
  // 先设置表单数据，再调用reset
  form.value = { ...row }
  // 单个用户ID，转换为数组格式用于多选显示
  form.value.userId = row.userId ? [row.userId] : []
  // 确保项目ID是数字类型
  form.value.projectId = Number(row.projectId)
  // 确保taskId是数字类型
  form.value.taskId = Number(row.taskId)
  // 确保duration是数字类型
  form.value.duration = Number(row.duration) || 0
  // 确保hourlyRate是数字类型
  form.value.hourlyRate = Number(row.hourlyRate) || 0
  
  // 不调用resetFields，避免清空数据
  
  
  // 先加载所有选项
  loadTasksByProject(form.value.projectId)
  loadMembersByProject(form.value.projectId)
  
  // 延迟打开对话框，确保数据加载完成
  setTimeout(() => {
    // 重新设置表单数据，防止被清空
    form.value = { ...row }
    form.value.userId = row.userId ? [row.userId] : []
    form.value.projectId = Number(row.projectId)
    form.value.taskId = Number(row.taskId)
    form.value.duration = Number(row.duration) || 0
    form.value.hourlyRate = Number(row.hourlyRate) || 0
    
    // 修改时只显示当前选中的任务和成员
    if (form.value.taskId) {
      const currentTask = taskOptions.value.find(t => t.taskId === form.value.taskId)
      if (currentTask) {
        taskOptions.value = [currentTask]
      }
    }
    
    if (form.value.userId && form.value.userId.length > 0) {
      const currentUsers = memberOptions.value.filter(m => form.value.userId.includes(m.userId))
      if (currentUsers.length > 0) {
        memberOptions.value = currentUsers
      }
    }
    
    isView.value = false
    open.value = true
    title.value = '修改时间记录'
  }, 100)
}

const submitForm = () => {
  formRef.value?.validate((valid: boolean) => {
    if (!valid) return
    
    // 如果选择了多个用户，为每个用户创建一条记录
    const userIds = Array.isArray(form.value.userId) ? form.value.userId : [form.value.userId]
    
    if (userIds.length === 0) {
      proxy?.$modal.msgError('请选择至少一个成员')
      return
    }
    
    // 为每个用户创建一条时间记录
    const promises = userIds.map(userId => {
      const payload = {
        ...form.value,
        userId: userId
      }
      return saveTime(payload)
    })
    
    Promise.all(promises).then((results) => {
      console.log('保存结果:', results)
      proxy?.$modal.msgSuccess(`成功保存 ${userIds.length} 条时间记录`)
      open.value = false
      // 清空查询条件，显示所有数据
      queryParams.projectId = undefined
      queryParams.taskId = undefined
      queryParams.userId = undefined
      queryParams.pageNum = 1
      getList()
    }).catch(error => {
      console.error('保存失败:', error)
      proxy?.$modal.msgError('保存失败: ' + error.message)
    })
  })
}

// 根据 userId 在成员列表中取昵称
const getNickName = (userId: string | number | undefined) => {
  if (!userId) return ''
  const found = memberOptions.value.find((m: any) => String(m.userId) === String(userId))
  return found?.nickName || ''
}


// 根据 userId 获取用户昵称（用于列表显示）
const getUserNickName = (userId: number | undefined) => {
  if (!userId) return ''
  
  // 尝试多种匹配方式
  let found = memberOptions.value.find((m: any) => m.userId === userId)
  if (!found) {
    found = memberOptions.value.find((m: any) => m.userId == userId)
  }
  if (!found) {
    found = memberOptions.value.find((m: any) => String(m.userId) === String(userId))
  }
  
  return found?.nickName || `用户${userId}`
}

// 将逗号分隔的用户编码映射为逗号分隔的昵称
const getNickNamesFromCsv = (userIdsCsv: string | undefined) => {
  if (!userIdsCsv) return ''
  const ids = String(userIdsCsv).split(',').map(s => s.trim()).filter(Boolean)
  if (!ids.length) return ''
  console.debug('转换用户编码为昵称:', { userIdsCsv, ids, memberOptions: memberOptions.value })
  const names = ids.map(id => {
    const found = memberOptions.value.find((m: any) => String(m.userId) === String(id))
    console.debug(`查找用户 ${id}:`, found)
    return found?.nickName || id
  })
  return names.join(', ')
}

// 获取用户昵称（使用项目成员数据）
const getUserNickNames = (userIdStr: string) => {
  if (!userIdStr) return ''
  console.log('getUserNickNames - userIdStr:', userIdStr)
  console.log('getUserNickNames - memberOptions:', memberOptions.value)
  
  // 保持字符串格式，避免大整数精度丢失
  const userIds = userIdStr.split(',').map(id => id.trim())
  console.log('getUserNickNames - userIds (字符串):', userIds)
  
  // 打印成员列表中所有用户的ID，帮助调试
  console.log('成员列表中的所有用户ID:', memberOptions.value.map(u => ({ userId: u.userId, nickName: u.nickName })))
  
  const names = userIds.map(id => {
    // 尝试多种匹配方式
    let user = memberOptions.value.find(u => u.userId == id) // 使用 == 进行宽松比较
    if (!user) {
      user = memberOptions.value.find(u => u.userId === String(id))
    }
    if (!user) {
      user = memberOptions.value.find(u => String(u.userId) === String(id))
    }
    if (!user) {
      user = memberOptions.value.find(u => u.userId === parseInt(id))
    }
    if (!user) {
      user = memberOptions.value.find(u => parseInt(u.userId) === parseInt(id))
    }
    
    console.log(`getUserNickNames - 查找用户ID "${id}" (类型: ${typeof id}):`, user)
    return user ? user.nickName : `用户${id}`
  })
  console.log('getUserNickNames - names:', names)
  return names.join(', ')
}

// 获取成员显示名称（用于标签显示）
const getMemberDisplayName = (userId: string) => {
  if (!userId) return ''
  const member = memberOptions.value.find(m => String(m.userId) === String(userId))
  return member ? member.nickName : `用户${userId}`
}

// 暴露给模板使用
defineExpose({
  getNickNamesFromCsv
})

const handleDelete = (row?: any) => {
  const delIds = row?.id ? [row.id] : ids.value
  proxy?.$modal.confirm('是否确认删除编号为"' + delIds.join(',') + '"的数据项？').then(() => {
    return delTime(delIds)
  }).then(() => {
    proxy?.$modal.msgSuccess('删除成功')
    getList()
  }).catch(() => {})
}

const cancel = () => {
  open.value = false
  reset()
}
</script>
